#include "oj_server/oj_server.h"
namespace ojlb {
namespace oj_server {


// public:
OjServer::OjServer(const uint16_t port, const std::string& host) {
    // 测试库的基本使用
    server_.set_pre_routing_handler([](const httplib::Request& req, httplib::Response& resp) { // 预发布路由处理器
        (void)req;
        (void)resp;
        oj_common::OjLog::info("统一处理所有预发布路由");
        return httplib::Server::HandlerResponse::Unhandled; // 请求未被预先处理, 依旧传递给后续路由
        // return httplib::Server::HandlerResponse::Handled; // 请求已被预先处理, 不会传递给后续路由
    });

    // TODO: 这里的路由绑定过于粗暴, 希望模块化, 至少文件化...
    server_.Get("/test", [](const httplib::Request& req, httplib::Response& resp) { // Get 请求
        (void)req;
        resp.set_content(R"({ "test": true })", "application/json");
    });

    server_.Post("/compile_and_run", [](const httplib::Request& req, httplib::Response& resp) { // Post 请求
        std::string in_json = req.body;
        std::string out_json;
        if (!in_json.empty()) {
            oj_compiler_run::OjCompileRun::start(in_json, out_json);
            resp.set_content(out_json, "application/json;charset=utf-8");
        }
    });

    server_.Put("/error", [](const httplib::Request& req, httplib::Response& resp) { // 带有奔溃的请求
        (void)req;
        (void)resp;
        throw std::runtime_error(R"({ "test": system error })");
    });

    server_.set_post_routing_handler([](const httplib::Request& req, httplib::Response& resp) { // 已发布路由处理器
        (void)req;
        (void)resp;
        oj_common::OjLog::info("统一处理所有已发布路由");
    });

    server_.set_error_handler([](const httplib::Request& req, httplib::Response& resp) { // 错误处理
        (void)req;
        resp.set_content(R"({ "test": user error })", "application/json");
    });

    server_.set_exception_handler([&](const httplib::Request& req, httplib::Response& resp, std::exception_ptr ep) { // 异常请求
        (void)req;
        try {
            std::rethrow_exception(ep);
        } catch (const std::runtime_error& e) {
            resp.set_content(R"({ "test": "system error }")", "application/json");
            server_.stop(); // 停止服务
        } catch (...) {
            resp.set_content(R"({ "test": "unknown error" })", "application/json");
            server_.stop();
        }
    });

    server_.set_logger([](const httplib::Request& req, const httplib::Response& resp) { // 日志输出
        oj_common::OjLog::info("Request: {} {}, Response: {}", req.method, req.path, resp.status);
    });

    server_.listen(host, port); // 监听状态
}


} // namespace oj_common end
} // namespace ojlb end